<?php
namespace App\Http\Controllers\Api;

use App\Http\Resources\Api\UserResource;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function me(Request $request)
    {
        $code = $request->code;
        if (!$this->mini_program) {
            return api()->failed('此商户未配置小程序商户信息或配置有误，无法正常使用');
        }
        $auth = $this->mini_program->auth->session($code);
        $weapp_openid = $auth['openid'];
        $user = User::where(['weapp_openid' => $weapp_openid])->first();
        if (!$user) {
            $user = User::create([
                'tenant_id' => $this->tenant->id,
                'nickname' => '用户' . \EasyWeChat\Kernel\Support\str_random(4),
                'weapp_openid' => $weapp_openid
            ]);
        }
        $return['auth'] = $auth;
        $token = '';
        $expires_in = '';
        if ($user) {
            $token = \Auth::guard('api')->fromUser($user);
            $user = new UserResource($user);
            $expires_in = \Auth::guard('api')->factory()->getTTL() * 60;
        }
        $return['user'] = $user;
        $return['meta']['token'] = $token;
        $return['meta']['expires_in'] = $expires_in;
        return api()->success($return);
    }

    public function updatePhone($id, Request $request)
    {
        $user = User::findOrFail($id);
        $cred = $request->only('code', 'openid', 'session_key', 'iv', 'encrypted_data');
        if (isset($cred['code']) && $cred['code']) {
            $auth = $this->mini_program->auth->session($cred['code']);
            $openid = $auth['openid'];
            $session_key = $auth['session_key'];
        } else {
            $openid = $cred['openid'];
            $session_key = $cred['session_key'];
        }
        $decrypted_data = $this->mini_program->encryptor->decryptData($session_key, $cred['iv'], $cred['encrypted_data']);
        $phone = $decrypted_data['phoneNumber'];
        $user->phone = $phone;
        $user->save();
        return api()->success($user);
    }
}
